/* eslint react/no-string-refs:0 */
import React, { PureComponent } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Grid, Button, Message, NumberPicker } from '@alifd/next';
import WebStorageCahe from 'web-storage-cache';
import request from '../../../../utils/request';
import { host, TEAM_RED, TEAM_BLUE, isSelectedMode, isSelectedCom } from '../../../../const';
import UploadDialog from '../../../../components/UploadDialog';
import XLSX from 'xlsx';

const { Row, Col } = Grid;
const wsCache = new WebStorageCahe();
export default class BattleForm extends PureComponent {
    static displayName = 'BattleForm';

    static propTypes = {};

    static defaultProps = {};

    constructor(props) {
        super(props);
        this.state = {
            tempVisible: false,
            fileObj: null,
            name1: '红队1号',
            name2: '蓝队1号',
            name3: '',
            name4: '',
            name5: '',
            name6: '',
            name7: '',
            name8: '',
            num1: '1',
            num2: '2',
            num3: '',
            num4: '',
            num5: '',
            num6: '',
            num7: '',
            num8: '',
            time: 600,
            isLoading: false,
        };
    }

    handleChange = (value, type, index) => {
        this.setState({
            [`${type}${index}`]: value,
        });
        console.log(this.state[`${type}${index}`]);
    }
    handleClick = () => {
        const {
            time,
        } = this.state;
        let flag = false;
        let formPage = {};
        for (let i = 1; i < 5; i++) {
            if (this.state[`name${2 * i}`] || this.state[`name${2 * i - 1}`] || this.state[`num${2 * i}`] || this.state[`num${2 * i - 1}`]) {
                if (!(this.state[`name${2 * i}`] && this.state[`name${2 * i - 1}`] && this.state[`num${2 * i}`] && this.state[`num${2 * i - 1}`])) {
                    Message.error(`第${i}行有数据为空`);
                    return;
                }
                flag = true;
            }
        }

        if (!flag) {
            Message.error('请至少输入一条数据');
            return;
        }
        if (!time) {
            Message.error('请输入时间');
            return;
        }
        //  校验编号唯一
        const numList = [];
        for (let i = 1; i < 5; i++) {
            if (this.state[`num${2 * i}`]) {
                numList.push(this.state[`num${2 * i}`]);
            }
            if (this.state[`num${2 * i - 1}`]) {
                numList.push(this.state[`num${2 * i - 1}`]);
            }
        }
        const mSet = new Set(numList);
        if (mSet.size !== numList.length) {
            Message.error('编号必须唯一!');
            return;
        }


        const list = [];

        for (let i = 1; i < 5; i++) {
            if (this.state[`name${2 * i}`]) {
                const item = {};
                item.index1 = 2 * i - 1;
                item.index2 = 2 * i;
                item.name1 = this.state[`name${2 * i - 1}`];
                item.name2 = this.state[`name${2 * i}`];
                item.num1 = this.state[`num${2 * i - 1}`];
                item.num2 = this.state[`num${2 * i}`];
                item.panel = i;
                list.push(item);
            }
        }


        const redList = list.map((i) => {
            const obj = {};
            obj.name = i.name1;
            obj.num = i.num1;
            obj.team = TEAM_RED;
            obj.index = i.panel * 2;
            return obj;
        });
        const blueList = list.map((i) => {
            const obj = {};
            obj.name = i.name2;
            obj.num = i.num2;
            obj.team = TEAM_BLUE;
            obj.index = i.panel * 2 - 1;

            return obj;
        });
        // time, redList,blueList传给后端
        console.log(redList, blueList);

        const lProtocol = wsCache.get('protocol');
        const selectedMode = isSelectedMode();
        if (!selectedMode) {
            return;
        }
        const selectedCom = isSelectedCom();
        if (!selectedCom) {
            return;
        }


        this.setState({
            isLoading: true,
        });
        request({
            method: 'POST',
            url: `${host}/bayonet/start/${lProtocol}`,
            data: {
                blueVestList: blueList,
                redVestList: redList,
                countdownTime: time,
            },
        }).then((res) => {
            this.setState({
                isLoading: false,
            });
            const code = res?.data?.code;
            if (code === 200) {
                formPage = {
                    time,
                    list,
                };

                wsCache.set('formPage', JSON.stringify(formPage));
                setTimeout(() => {
                    window.location.href = '#/poke/show';
                }, 300);
            }
        }, () => {
            this.setState({
                isLoading: false,
            });
        });
    }
    uploadChange = (info) => {
        if (info && info[0]) {
            this.setState({
                fileObj: info[0],
            });
        }
    }
    handleOk = () => {
        const { fileObj } = this.state;

        if (!fileObj) {
            Message.error('请选择模板');
        }

        this.onImportExcel(fileObj.originFileObj);
    }
    handleCancle = () => {
        this.setState({
            tempVisible: false,
            fileObj: null,

        });
    }
    handleRemove = () => {
        this.setState({
            fileObj: null,
        });
    }
    showTempleDialog = () => {
        this.setState({
            tempVisible: true,
        });
    }

    onImportExcel = (file) => {
        // 通过FileReader对象读取文件
        const fileReader = new FileReader();
        fileReader.onload = (event) => {
            try {
                const { result } = event.target;
                // 以二进制流方式读取得到整份excel表格对象
                const workbook = XLSX.read(result, { type: 'binary' });
                let redData = []; // 红队数据
                let blueData = []; // 蓝队数据
                let timeData = []; // 时间
                // 遍历每张工作表进行读取（这里默认只读取第一张表）
                for (const sheet in workbook.Sheets) {
                    if (workbook.Sheets.hasOwnProperty(sheet)) {
                        // 利用 sheet_to_json 方法将 excel 转成 json 数据
                        // break; // 如果只取第一张表，就取消注释这行
                        if (sheet.indexOf('红队') > -1) {
                            redData = redData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                        }
                        if (sheet.indexOf('蓝队') > -1) {
                            blueData = blueData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                        }
                        if (sheet.indexOf('比赛时间') > -1) {
                            timeData = timeData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                        }
                    }
                }

                this.handleData(redData, blueData, timeData);
            } catch (e) {
                console.log(e);
                // 这里可以抛出文件类型错误不正确的相关提示
                console.log('文件类型不正确');
            }
        };
        // 以二进制方式打开文件
        fileReader.readAsBinaryString(file);
    }
    handleData = (redData, blueData, timeData) => {
        const time = timeData[0]['比赛时间(分钟)'];
        redData.forEach((i, index) => {
            if (i['红队姓名']) {
                const nameStr = `name${index * 2 + 1}`;
                const numStr = `num${index * 2 + 1}`;
                this.setState({
                    [nameStr]: i['红队姓名'],
                    [numStr]: i['红队编号'],
                });
            }
        });
        blueData.forEach((i, index) => {
            if (i['蓝队姓名']) {
                const nameStr = `name${(index + 1) * 2}`;
                const numStr = `num${(index + 1) * 2}`;
                this.setState({
                    [nameStr]: i['蓝队姓名'],
                    [numStr]: i['蓝队编号'],
                });
            }
        });
        this.setState({
            time: time * 60, // 转化分钟为秒
        });
        this.handleCancle();
    }

    render() {
        return (
            <div className="user-form">
                <IceContainer >


                    <Row>
                        <Col>
                            <div className="flex justify-center">红方</div>
                        </Col>
                        <Col>
                            <div className="flex justify-center">蓝方</div>
                        </Col>
                    </Row>
                    {
                        [1, 2, 3, 4].map(item => (<Row key={item} >
                            <Col>
                                <div className="flex justify-center ma">
                                    <Input
                                        addonTextBefore="名字"
                                        size="large"
                                        placeholder="名字"
                                        value={this.state[`name${2 * item - 1}`]}
                                        style={{ width: '180px' }}
                                        onChange={(value) => {
                                            this.handleChange(value, 'name', 2 * item - 1);
                                        }}
                                        maxLength={8}
                                    />&nbsp;&nbsp;
                                    <NumberPicker
                                        addonTextBefore="编号"
                                        value={this.state[`num${2 * item - 1}`]}
                                        size="large"
                                        min={1}
                                        placeholder="编号(唯一)"
                                        onChange={(value) => {
                                            this.handleChange(value, 'num', 2 * item - 1);
                                        }}
                                        style={{ width: '180px' }}
                                        maxLength={8}
                                    />
                                </div>
                            </Col>
                            <Col>
                                <div className="flex justify-center ma">
                                    <Input
                                        addonTextBefore="名字"
                                        size="large"
                                        value={this.state[`name${2 * item}`]}
                                        placeholder="名字"
                                        style={{ width: '180px' }}
                                        maxLength={8}
                                        onChange={(value) => {
                                            this.handleChange(value, 'name', item * 2);
                                        }}
                                    />&nbsp;&nbsp;
                                    <NumberPicker
                                        addonTextBefore="编号"
                                        value={this.state[`num${2 * item}`]}
                                        size="large"
                                        placeholder="编号(唯一)"
                                        min={1}
                                        style={{ width: '180px' }}
                                        maxLength={8}
                                        onChange={(value) => {
                                            this.handleChange(value, 'num', item * 2);
                                        }}
                                    />
                                </div>
                            </Col>
                        </Row>))
                    }
                    <Row>
                        <Col>
                            <div className="flex justify-center">

                                <Input
                                    addonTextBefore="时间(秒) "
                                    value={this.state.time}
                                    size="large"
                                    placeholder="600"
                                    style={{ width: '360px' }}
                                    maxLength={18}
                                    onChange={(value) => {
                                        this.setState({
                                            time: value,
                                        });
                                    }}
                                />
                            </div>
                        </Col>
                        <Col>
                            <div className="flex justify-center" />
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <div className="flex justify-center">
                                <Button type="primary" onClick={this.handleClick} loading={this.state.isLoading} className="pa" >开始</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                                <Button
                                    type="primary"

                                    style={{
                                        background: 'orange',
                                    }}
                                    onClick={this.showTempleDialog}
                                    loading={this.state.isLoading}
                                    className="pa"
                                >导入配置</Button>&nbsp;&nbsp;&nbsp;&nbsp;

                                <Button

                                    type="primary"
                                    style={{
                                        background: '#64dff3',
                                    }}
                                    component="a"
                                    href="/temp/刺杀-人员导入格式.xls"
                                >

                                    下载模板


                                </Button>
                            </div>

                        </Col>


                    </Row>
                    <UploadDialog
                        visible={this.state.tempVisible}
                        handleOk={this.handleOk}
                        handleCancle={this.handleCancle}
                        uploadChange={this.uploadChange}
                        onRemove={this.handleRemove}
                    />
                </IceContainer>
            </div>
        );
    }
}

